#include "time0.h"
volatile uint32_t uwTick = 0;
 
void timer_irq_handler(void); 
volatile uint8_t tick_flag = 0;

void timer0_init(void)
{
    // Configure timer to generate update event every 1ms
    tim_init(TIM0, TIM_MODE_CONT, TIM_SRC_HOSC, TIM_PSC_1);
    tim_set_period(TIM0, 24000000UL / 1000UL);
    tim_int_enable(TIM0);
    // IRQ configuration
    intc_set_irq_handler(IRQ_TIMER0, timer_irq_handler);
    intc_enable_irq(IRQ_TIMER0);

    tim_start(TIM0);
}

void timer_irq_handler(void)
{ 
    tim_clear_irq(TIM0);
    tick_flag = 1; 
    uwTick++;
}

//1ms delay
void delay(uint32_t t)
{
    while (1)
    {
        if (t == 0)
            return;
        if (tick_flag == 1)
        {
            tick_flag = 0;
            t--;
        }
    }
}
